import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state: {
        list: JSON.parse(sessionStorage.getItem("list")) || [],
        info: JSON.parse(sessionStorage.getItem("info")) || {},
        mInfo:{}
    },
    mutations: {
        savem(state,a){
            state.mInfo=a;
        },
        saveInfo(state, a) {
            state.info = a;
            sessionStorage.setItem("info", JSON.stringify(state.info))
        },
        addp(state, a) {
            console.log(a);
            var flag = false;
            state.list.some((item, index, arr) => {
                if (item.id == a.id) {
                    item.count++;
                    flag = true;
                    return true;
                }
            });
            if (!flag) {
                state.list.push(a);
            }
            sessionStorage.setItem("list", JSON.stringify(state.list));
        },
        sub(state, a) {
            state.list.some((item, index, list) => {
                if (item.id == a.id) {
                    if (item.count <= 1) {
                        list.splice(index, 1);
                    } else {
                        item.count--;
                    }
                    return true;
                }
            })
            sessionStorage.setItem("list", JSON.stringify(state.list));
        },
        add(state, a) {
            state.list.some((item, index, arr) => {
                if (item.id == a.id) {
                    item.count++;
                    return true;
                }
            })
            sessionStorage.setItem("list", JSON.stringify(state.list));
        },
        change(state, v) {
            state.list.some((item, index, arr) => {
                if (item.id == v.id) {
                    item.count = v.count;
                    return true;
                }
            })
            sessionStorage.setItem("list", JSON.stringify(state.list));
        }
    },
    getters: {
        allCount(state) {
            var count = 0;
            state.list.forEach(item => {
                count += item.count;
            });
            return count;
        }
    }
})

export default store;